package ru.amse.ilyin.analyzer.impl;

import java.io.File;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;

import ru.amse.ilyin.analyzer.Package;
import ru.amse.ilyin.analyzer.Analyzer;

/**
 * Implementation of {@link Analyzer} interface.
 * 
 * @author Alexander Ilyin
 */
public class AnalyzerImpl implements Analyzer {
	public Set<Package> getPackages(File rootPackage) {
		if (rootPackage == null) {
			throw new IllegalArgumentException("null");
		}
		if ((!rootPackage.exists()) ||
			(!rootPackage.isDirectory())) {
			throw new IllegalArgumentException(
					"package doesn't exist: " + rootPackage.getAbsolutePath());
		}
		
		final File absolutePackageName = rootPackage.getAbsoluteFile(); 
		
		final Set<Package> result = new HashSet<Package>();
		
		final Queue<File> queue = new LinkedList<File>();
		queue.offer(absolutePackageName);
		addPackageIfNeeded(result, absolutePackageName, absolutePackageName);
		while(!queue.isEmpty()) {
			final File aPackage = queue.remove();
			for (File child : aPackage.listFiles()) {
				if (child.isDirectory()) {
					queue.offer(child);
					addPackageIfNeeded(result, absolutePackageName, child);
				}
			}
		}
		
		return result;
	}
	
	private void addPackageIfNeeded(
			Set<Package> result, 
			File rootPackage, 
			File aPackage
	) {
		if (aPackage.listFiles(new ClassFileFilter()).length > 0) {
			result.add(new PackageImpl(
					aPackage,
					getPackageName(rootPackage, aPackage)
			));
		}
	}
	
	private String getPackageName(File rootPackage, File aPackage) {
		assert (rootPackage.isAbsolute()) : "filename isn't absolute";
		assert (aPackage.isAbsolute()) : "filename isn't absolute";
		
		final String relativeName =
				rootPackage.getName() + 
				aPackage.getPath().substring(rootPackage.getPath().length());
		
		return relativeName.replace(File.separatorChar, '.');
	}
}
